package com.one.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


public class TokenUtils {

    //常量
    public static final long EXPIRE = 1000 * 60 * 60 * 24; //token过期时间
    public static final String APP_SECRET = "Pc83x7RJ0uT2djtbwZFWVQsKqXYAmHyz"; //秘钥
    //生成token字符串的方法
    public static String getJwtToken(String id) {

        String JwtToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))

                .claim("id", id)  //设置token主体部分 ，存储用户信息
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();

        return JwtToken;
    }


    public static boolean checkToken(String token) {
        if (StringUtils.hasLength(token)) {
            try {
                Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static String getUserID(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token == null || token.equals("") || !checkToken(token)) return "";
        Claims claims = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token).getBody();
        return (String) claims.get("id");
    }
//    public static UserEntity getUser(HttpServletRequest request) {
//        String token= request.getHeader("Authorization");
//        if (token == null || token.equals("")) new BizException(ErrorEnum.SIGNATURE_NOT_MATCH.getResultCode(),"你没有权限");
//        System.out.println(token);
//        Claims claims = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token).getBody();
//        String id = (String) claims.get("id");
//        String userType = (String) claims.get("userType");
//        UserEntity userEntity = new UserEntity();
//        userEntity.setId((String) claims.get("id"));
//        userEntity.setRoleType((String) claims.get("roleType"));
//        return userEntity;
//    }
//    /**
//     * 直接通过这个方法得到存储在token中的UserId
//     * @param request
//     * @return
//     */
//    public static String getMemberIdByJwtToken(HttpServletRequest request) {
//        String token = request.getHeader("Authorization");
////        token = getJwtToken(Id,UserType);
//        if (token == null || token.equals("")) return "";
//        Claims claims = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token).getBody();
//        return (String) claims.get("id");
//    }
}
